package backend

import (
	"context"
	"fmt"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"miaoyuadmin/api/backend/response"
	"miaoyuadmin/internal/enums/roleenum"
	"miaoyuadmin/internal/enums/userenum"
	"miaoyuadmin/internal/model"
	"strings"

	"miaoyuadmin/api/backend"

	"miaoyuadmin/internal/service"

	"github.com/gogf/gf/v2/util/gconv"
)

type userCtl struct{}

var User = userCtl{}

// Info should be authenticated to view.
// It is the get user data handler
func (c *userCtl) Info(ctx context.Context, req *backend.UserGetInfoReq) (res *backend.UserGetInfoRes, err error) {
	return &backend.UserGetInfoRes{
		Id:          gconv.Int(service.Auth().GetIdentity(ctx)),
		IdentityKey: service.Auth().IdentityKey,
		Payload:     service.Auth().GetPayload(ctx),
	}, nil
}

func (c *userCtl) Index(ctx context.Context, req *backend.UserIndexReq) (res *backend.UserIndexRes, err error) {
	response.BuildTpl(g.RequestFromCtx(ctx), "public/layout.html").WriteTpl(g.MapStrAny{
		"mainTpl": "user/info/index.html",
		"footTpl": "user/info/index.js.html",
		"title":   "职级管理",
	})

	return
}
func (c *userCtl) Add(ctx context.Context, req *backend.UserAddReq) (res *backend.UserAddRes, err error) {
	response.BuildTpl(g.RequestFromCtx(ctx), "public/layout.html").WriteTpl(g.MapStrAny{
		"mainTpl":    "user/info/add.html",
		"footTpl":    "user/info/add.js.html",
		"siteName":   "控制台",
		"statusList": userenum.ListStatusMap,
	})

	return
}

func (c *userCtl) Edit(ctx context.Context, req *backend.UserEditReq) (res *backend.UserEditRes, err error) {
	resId := req.ResId

	itemRes, resErr := service.User().GetItemById(ctx, resId)
	if resErr != nil {
		err = resErr
		response.UniResp(g.RequestFromCtx(ctx), err.Error(), "")
		return
	}
	response.BuildTpl(g.RequestFromCtx(ctx), "public/layout.html").WriteTpl(g.MapStrAny{
		"mainTpl":    "user/info/add.html",
		"footTpl":    "user/info/edit.js.html",
		"siteName":   "控制台",
		"data":       itemRes,
		"statusList": userenum.ListStatusMap,
	})
	return
}

func (c *userCtl) DelDo(ctx context.Context, req *backend.UserDelDoReq) (res *backend.UserDelDoRes, err error) {
	resId := req.ResId
	commonJson := response.CommonResp(g.RequestFromCtx(ctx))
	_, resErr := service.User().Del(ctx, resId)
	if resErr != nil {
		err = resErr
		commonJson.SetErrorJsonExit(err.Error())
		return
	}
	commonJson.SetSuccessJsonExit("操作成功", nil)
	return

}

func (c *userCtl) ListDo(ctx context.Context, req *backend.UserListDoReq) (res *backend.UserListDoRes, err error) {

	commonJson := response.CommonResp(g.RequestFromCtx(ctx))
	listOptions := model.CommonListInput{Page: 1, Limit: 10}
	if req.Page <= 0 {
		listOptions.Page = 1
	} else {
		listOptions.Page = req.Page
	}
	if req.Limit <= 0 {
		listOptions.Limit = 10
	} else {
		listOptions.Limit = req.Limit
	}
	if req.Keywords = strings.Trim(req.Keywords, " "); req.Keywords != "" {
		listOptions.Keywords = req.Keywords
	}
	listRes, count, resErr := service.User().GetPageList(ctx, listOptions)
	if resErr != nil {
		err = resErr
		return
	}
	resData := response.JsonResult{Data: listRes, Count: count, Msg: "ok"}
	commonJson.SetSuccessMapExit(resData)

	return
}
func (c *userCtl) SubmitDo(ctx context.Context, req *backend.UserSubmitDoReq) (res *backend.UserSubmitDoRes, err error) {
	var submitInput model.UserSubmitInput
	commonJson := response.CommonResp(g.RequestFromCtx(ctx))
	err = gconv.Scan(req, &submitInput)
	fmt.Println("用户提交数据", submitInput)
	if err != nil {
		return
	}
	resId := req.ResId
	if resId != 0 {
		_, err = service.User().Edit(ctx, submitInput, resId)
		if err != nil {
			commonJson.SetErrorJsonExit(err.Error())
		} else {
			commonJson.SetSuccessJsonExit("修改成功", nil)
		}
		return
	} else {
		_, err = service.User().Add(ctx, submitInput)
		if err != nil {
			commonJson.SetErrorJsonExit(err.Error())
		}

		commonJson.SetSuccessJsonExit("添加成功", nil)
	}

	return
}
func (c *userCtl) Grant(ctx context.Context, req *backend.UserGrantReq) (res *backend.UserGrantRes, err error) {
	//获取所有菜单以及该角色的菜单
	userId := req.ResId
	roleList, resErr := service.Role().GetAllList(ctx, nil)
	if resErr != nil {
		err = resErr
		return
	}
	roleLen := len(roleList)
	roleOutputList := make([]model.RoleWithTagOutput, roleLen)
	for k, v := range roleList {
		roleOutputList[k].Title = v.Title
		roleOutputList[k].Id = v.Id
		roleOutputList[k].CodeName = v.CodeName
		roleOutputList[k].Bak = v.Bak
		if v.Status == gconv.Int(roleenum.Enable) {
			roleOutputList[k].IsEnable = true
		} else {
			roleOutputList[k].IsEnable = false
		}
	}
	myRoleList, _ := service.Role().GetRoleListByUserId(ctx, userId)
	fmt.Println("myroleList", myRoleList)
	myRoleListJson, _ := gjson.EncodeString(myRoleList)
	response.BuildTpl(g.RequestFromCtx(ctx), "public/layout.html").WriteTpl(g.MapStrAny{
		"mainTpl":    "user/info/grant.html",
		"footTpl":    "user/info/grant.js.html",
		"siteName":   "控制台",
		"listData":   roleOutputList,
		"myRoleJson": myRoleListJson,
		"resId":      userId,
	})

	return
}
func (c *userCtl) GrantSubmitDo(ctx context.Context, req *backend.UserGrantSubmitDoReq) (res *backend.UserGrantSubmitDoRes, err error) {
	userId := req.ResId
	roleList := req.RoleList
	commonJson := response.CommonResp(g.RequestFromCtx(ctx))
	_, resErr := service.User().GetItemById(ctx, userId)

	if resErr != nil {
		commonJson.SetErrorJsonExit("请求数据不存在，请确认后提交！")
	}
	fmt.Println("提交菜单列表", roleList)
	_, sqlErr := service.User().Grant(ctx, userId, roleList)
	if sqlErr != nil {
		commonJson.SetErrorJsonExit(sqlErr.Error())
	}
	commonJson.SetSuccessJsonExit("提交成功", nil)

	return
}
